package cmd

import (
	"context"
	"fmt"
	"runtime"
	"time"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"

	"goldtree/internal"
	"goldtree/internal/controller"
	"goldtree/internal/middleware"
	"goldtree/internal/service"
)

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			// 打印启动横幅
			printStartupBanner()

			// 打印系统信息
			printSystemInfo(ctx)

			g.Log().Info(ctx, "正在初始化数据库...")
			// 初始化数据库
			if err := internal.InitDB(ctx); err != nil {
				g.Log().Fatal(ctx, "Failed to initialize database:", err)
				return err
			}
			g.Log().Info(ctx, "数据库初始化完成")

			// 初始化系统数据（创建默认管理员等）
			g.Log().Info(ctx, "正在初始化系统数据...")
			if err := service.Init.InitializeSystem(ctx); err != nil {
				g.Log().Warning(ctx, "Failed to initialize system data:", err)
				// 不阻断系统启动，但记录警告
			}
			g.Log().Info(ctx, "系统数据初始化完成")

			s := g.Server()

			// 静态文件服务（web管理界面）
			s.SetServerRoot("./web")
			s.AddStaticPath("/", "./web")
			s.AddStaticPath("/css", "./web/css")
			s.AddStaticPath("/js", "./web/js")

			s.Group("/", func(group *ghttp.RouterGroup) {
				group.Middleware(ghttp.MiddlewareCORS)
				group.Bind(
					controller.Hello,
				)
			})

			// 公开API路由组（无需认证）
			s.Group("/api/v1/public", func(group *ghttp.RouterGroup) {
				group.Middleware(ghttp.MiddlewareCORS)

				// 用户认证路由
				group.Group("/auth", func(authGroup *ghttp.RouterGroup) {
					authGroup.POST("/register", controller.UserCtrl.Register)
					authGroup.POST("/login", controller.UserCtrl.Login)
					authGroup.POST("/refresh", controller.UserCtrl.RefreshToken)
					authGroup.POST("/validate", controller.UserCtrl.ValidateToken)
				})
			})

			// 需要认证的API路由组
			s.Group("/api/v1", func(group *ghttp.RouterGroup) {
				group.Middleware(ghttp.MiddlewareCORS)
				group.Middleware(middleware.Auth) // 添加认证中间件

				// 股票管理路由
				group.Group("/stocks", func(stockGroup *ghttp.RouterGroup) {
					stockGroup.GET("/", controller.StockCtrl.GetList)
					stockGroup.POST("/", controller.StockCtrl.Create)
					stockGroup.POST("/batch", controller.StockCtrl.BatchCreate)
					stockGroup.POST("/import", controller.StockCtrl.Import)
					stockGroup.POST("/validate", controller.StockCtrl.Validate)
					stockGroup.POST("/bulk-status", controller.StockCtrl.BulkUpdateStatus)
					stockGroup.POST("/sync", controller.StockCtrl.SyncMarketData)
					stockGroup.GET("/:id", controller.StockCtrl.GetById)
					stockGroup.PUT("/:id", controller.StockCtrl.Update)
					stockGroup.DELETE("/:id", controller.StockCtrl.Delete)
					stockGroup.GET("/code/:code", controller.StockCtrl.GetByCode)
					stockGroup.GET("/industries", controller.StockCtrl.GetIndustryList)
					stockGroup.GET("/sectors", controller.StockCtrl.GetSectorList)
					stockGroup.GET("/markets", controller.StockCtrl.GetMarketList)
					stockGroup.GET("/statistics", controller.StockCtrl.GetStatistics)
				})

				// 股票池管理路由
				group.Group("/stock-pools", func(poolGroup *ghttp.RouterGroup) {
					poolGroup.GET("/", controller.StockPoolCtrl.GetList)
					poolGroup.POST("/", controller.StockPoolCtrl.Create)
					poolGroup.GET("/:id", controller.StockPoolCtrl.GetById)
					poolGroup.GET("/:id/detail", controller.StockPoolCtrl.GetDetail)
					poolGroup.PUT("/:id", controller.StockPoolCtrl.Update)
					poolGroup.DELETE("/:id", controller.StockPoolCtrl.Delete)
					poolGroup.GET("/active", controller.StockPoolCtrl.GetActiveList)
					// 成员管理
					poolGroup.POST("/members", controller.StockPoolCtrl.AddMember)
					poolGroup.POST("/members/batch", controller.StockPoolCtrl.BatchAddMembers)
					poolGroup.DELETE("/members", controller.StockPoolCtrl.RemoveMember)
					poolGroup.GET("/members", controller.StockPoolCtrl.GetMembers)
				})

				// 策略管理路由
				group.Group("/strategies", func(strategyGroup *ghttp.RouterGroup) {
					strategyGroup.GET("/", controller.Strategy.GetList)
					strategyGroup.POST("/", controller.Strategy.Create)
					strategyGroup.GET("/:id", controller.Strategy.GetById)
					strategyGroup.GET("/:id/detail", controller.Strategy.GetDetail)
					strategyGroup.PUT("/:id", controller.Strategy.Update)
					strategyGroup.DELETE("/:id", controller.Strategy.Delete)
					strategyGroup.POST("/:id/start", controller.Strategy.Start)
					strategyGroup.POST("/:id/stop", controller.Strategy.Stop)
					strategyGroup.GET("/:id/logs", controller.Strategy.GetLogs)
					strategyGroup.GET("/types", controller.Strategy.GetTypeList)
					strategyGroup.GET("/active", controller.Strategy.GetActiveList)
					strategyGroup.GET("/running", controller.Strategy.GetRunningList)
				})

				// 标签管理路由
				group.Group("/tags", func(tagGroup *ghttp.RouterGroup) {
					tagGroup.GET("/", controller.TagCtrl.GetList)
					tagGroup.POST("/", controller.TagCtrl.Create)
					tagGroup.GET("/:id", controller.TagCtrl.GetById)
					tagGroup.GET("/:id/detail", controller.TagCtrl.GetDetail)
					tagGroup.PUT("/:id", controller.TagCtrl.Update)
					tagGroup.DELETE("/:id", controller.TagCtrl.Delete)
					tagGroup.GET("/active", controller.TagCtrl.GetActiveList)
					tagGroup.GET("/categories", controller.TagCtrl.GetCategoryList)
					tagGroup.GET("/category/:category", controller.TagCtrl.GetByCategory)
					tagGroup.GET("/tree", controller.TagCtrl.GetTagTree)
					// 标签关联管理
					tagGroup.POST("/assign", controller.TagCtrl.AssignTag)
					tagGroup.POST("/assign/batch", controller.TagCtrl.BatchAssignTag)
					tagGroup.DELETE("/assign", controller.TagCtrl.RemoveTag)
					tagGroup.GET("/stocks", controller.TagCtrl.GetStockTags)
					tagGroup.GET("/stocks/:tag_id", controller.TagCtrl.GetTagStocks)
				})

				// 用户管理路由（需要认证）
				group.Group("/user", func(userGroup *ghttp.RouterGroup) {
					userGroup.GET("/profile", controller.UserCtrl.GetProfile)
					userGroup.PUT("/profile", controller.UserCtrl.UpdateProfile)
					userGroup.POST("/change-password", controller.UserCtrl.ChangePassword)
					userGroup.POST("/logout", controller.UserCtrl.Logout)
					userGroup.GET("/info", controller.UserCtrl.GetUserInfo)
				})

				// 数据查询API路由
				group.Group("/data", func(dataGroup *ghttp.RouterGroup) {
					// 股票数据查询
					dataGroup.GET("/stocks", controller.DataQueryCtrl.QueryStocks)
					dataGroup.GET("/stocks/search", controller.DataQueryCtrl.SearchStocks)
					dataGroup.GET("/stocks/:code", controller.DataQueryCtrl.GetStockDetail)
					dataGroup.GET("/stocks/:code/realtime", controller.DataQueryCtrl.GetRealtimeData)

					// K线数据查询
					dataGroup.GET("/kline", controller.DataQueryCtrl.QueryKLineData)

					// 市场数据查询
					dataGroup.GET("/market", controller.DataQueryCtrl.QueryMarketData)
					dataGroup.GET("/market/overview", controller.DataQueryCtrl.GetMarketOverview)
					dataGroup.POST("/market/realtime/batch", controller.DataQueryCtrl.BatchGetRealtimeData)

					// 行业数据查询
					dataGroup.GET("/industry/overview", controller.DataQueryCtrl.GetIndustryOverview)
					dataGroup.GET("/industry/list", controller.DataQueryCtrl.GetIndustryList)

					// 市场列表
					dataGroup.GET("/market/list", controller.DataQueryCtrl.GetMarketList)

					// 交易信号查询
					dataGroup.GET("/signals", controller.DataQueryCtrl.QuerySignals)

					// 统计数据
					dataGroup.GET("/statistics", controller.DataQueryCtrl.GetStatistics)
				})
			})

			// 打印路由信息
			printRouteInfo(ctx)

			// 打印服务器启动信息
			printServerInfo(ctx)

			g.Log().Info(ctx, "🚀 Goldtree服务器启动中...")
			s.Run()
			return nil
		},
	}
)

// printStartupBanner 打印启动横幅
func printStartupBanner() {
	fmt.Println("")
	fmt.Println("========================================")
	fmt.Println("    ______      __    __              ")
	fmt.Println("   / ____/___  / /___/ /_________  ___ ")
	fmt.Println("  / / __/ __ \\/ / __  / __/ ___/ _ \\/ _ \\")
	fmt.Println(" / /_/ / /_/ / / /_/ / /_/ /  /  __/  __/")
	fmt.Println(" \\____/\\____/_/\\__,_/\\__/_/   \\___/\\___/ ")
	fmt.Println("")
	fmt.Println("    股票量化交易分析系统")
	fmt.Println("    Gold Tree Trading System")
	fmt.Println("========================================")
	fmt.Println("")
}

// printSystemInfo 打印系统信息
func printSystemInfo(ctx context.Context) {
	g.Log().Info(ctx, "🖥️  系统信息:")
	g.Log().Infof(ctx, "   Go版本: %s", runtime.Version())
	g.Log().Infof(ctx, "   操作系统: %s/%s", runtime.GOOS, runtime.GOARCH)
	g.Log().Infof(ctx, "   CPU核心数: %d", runtime.NumCPU())
	g.Log().Infof(ctx, "   启动时间: %s", time.Now().Format("2006-01-02 15:04:05"))
	g.Log().Info(ctx, "")
}

// printRouteInfo 打印路由信息
func printRouteInfo(ctx context.Context) {
	g.Log().Info(ctx, "🛣️  API路由信息:")
	g.Log().Info(ctx, "   公开路由:")
	g.Log().Info(ctx, "     POST /api/v1/public/auth/register  - 用户注册")
	g.Log().Info(ctx, "     POST /api/v1/public/auth/login     - 用户登录")
	g.Log().Info(ctx, "     POST /api/v1/public/auth/refresh   - 刷新令牌")
	g.Log().Info(ctx, "     POST /api/v1/public/auth/validate  - 验证令牌")
	g.Log().Info(ctx, "")
	g.Log().Info(ctx, "   认证路由:")
	g.Log().Info(ctx, "     GET  /api/v1/stocks                - 股票管理")
	g.Log().Info(ctx, "     GET  /api/v1/stock-pools          - 股票池管理")
	g.Log().Info(ctx, "     GET  /api/v1/strategies            - 策略管理")
	g.Log().Info(ctx, "     GET  /api/v1/tags                  - 标签管理")
	g.Log().Info(ctx, "     GET  /api/v1/data                  - 数据查询")
	g.Log().Info(ctx, "     GET  /api/v1/user                  - 用户信息")
	g.Log().Info(ctx, "")
}

// printServerInfo 打印服务器信息
func printServerInfo(ctx context.Context) {
	config := g.Cfg()
	address := config.MustGet(ctx, "server.address", ":8080").String()

	g.Log().Info(ctx, "🌐 服务器配置:")
	g.Log().Infof(ctx, "   监听地址: %s", address)
	g.Log().Infof(ctx, "   数据库: SQLite (./data/goldtree.db)")
	g.Log().Infof(ctx, "   默认管理员: admin / admin123")
	g.Log().Info(ctx, "")
	g.Log().Info(ctx, "📋 访问链接:")
	port := address
	if port[0] == ':' {
		port = "http://localhost" + port
	} else {
		port = "http://" + port
	}
	g.Log().Infof(ctx, "   主页: %s", port)
	g.Log().Infof(ctx, "   API文档: %s/swagger", port)
	g.Log().Infof(ctx, "   健康检查: %s/api/health", port)
	g.Log().Info(ctx, "")
}
